#define globusPin 2

#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 4, 5, 6);

int lastPowerState = 0;
unsigned long  turnOnTimer = 0;
unsigned long  turnOffTimer = 0;
int turnOnTime = 15000;
int turnOffTime = 8000;
int powerState = 0;

int lcdMode = 0;

void setup(){
  Serial.begin(115200);

  pinMode(globusPin,INPUT); 
  digitalWrite(globusPin,HIGH);

  digitalWrite(17, HIGH);  
  digitalWrite(18, HIGH);  


  ethernetSetup();
  lcdSetup();

  lastPowerState =  analogRead(4) > 30;
  powerState = !lastPowerState;
}

void loop(){
  if(digitalRead(globusPin) == LOW){
    Serial.write('b'); 
    delay(200);
  }


  if(analogRead(4) > 30 != lastPowerState && turnOnTimer < millis() && turnOffTimer < millis()){
    lastPowerState = analogRead(4) > 30;
    if(lastPowerState == 0 && powerState != 1){
      //Turn on
      powerState = 1;
      lcd.clear();
      lcd.print("TURNING ON");
      turnOnTimer = millis() + turnOnTime;

      wakeComputers(); 
    } 
    else if(powerState != 0) {
      powerState = 0;
      lcd.clear();
      lcd.print("TURNING OFF");
      turnOffTimer = millis() + turnOffTime;
      Serial.write('o'); 

    }
    lcdMode = 1;
  } 

  if(turnOnTimer > millis() || turnOffTimer > millis()){
    int progress = 0;
    if(turnOnTimer > millis() ){
      progress = 14-(14*(turnOnTimer - millis())) / turnOnTime;
    }
    else {
      progress = (14*(turnOffTimer - millis())) / turnOffTime;
    }

    if(millis()%100 == 0 && progress >= 0){
      lcd.setCursor(0,1);
      lcd.write(1);
      for(int i=0;i<progress;i++){
        lcd.write(0);
      }
      for(int i=0;i<14-progress;i++){
        lcd.print(" "); 
      }
      lcd.write(2);
    }
  } 
  else if(lcdMode == 1){
    lcdMode = 0;
    lcd.clear(); 
  }


}












